from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from QQLoginTool.QQtool import OAuthQQ
# Create your views here.
from oauth.utils import generic_access_token

"""
用户点击 qq登录按钮的时候，前端发送一个ajax请求，后端生成的url返回给前端

GET      /oauth/qq/statues/
"""
from django.conf import settings
# from mall import settings
class OauthQQURLView(APIView):
	"""
	生成的url
	"""

	def get(self,request):
		state = '/'
		# 1.创建对象
		oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
						client_secret=settings.QQ_CLIENT_SECRET,
						redirect_uri=settings.QQ_REDIRECT_URI,
						state=state)

		# 2.调用对象的方法，获取url
		url = oauth.get_qq_url()
		# url = 'https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=101474184&redirect_uri=http://www.meiduo.site:8080/oauth_callback.html&state=test'

		return Response({'login_url': url})

"""
当用户扫描成功后，腾讯服务器会生成一个code,我们前端需要将code返回给后端
接收code，通过code换取token

GET /auth/qq/users/?code=xxx

"""
from rest_framework import status
from .models import OAuthQQUser
from .serializers import OauthQQUserSerilizer
class OauthQQUserView(APIView):

	def get(self,request):
		# 1.接收code
		code = request.query_params.get('code')
		if code is None:
			return Response(status=status.HTTP_400_BAD_REQUEST)
		# 2.通过code换取token

		oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
						client_secret=settings.QQ_CLIENT_SECRET,
						redirect_uri=settings.QQ_REDIRECT_URI)

		access_token = oauth.get_access_token(code)

		openid = oauth.get_open_id(access_token)

		# 获取到openid之后，我们要查寻数据库，是否含有这个openid
		try:
			qquser = OAuthQQUser.objects.get(openid=openid)
		except OAuthQQUser.DoesNotExist:
			# 如果没有 则说明用户没绑定过
			"""
			1.openid是比较敏感的数据，我们最好对这个数据进行一个加密
			2.我们这个数据最好设置一个有效期
			"""

			# 要将openid进行加密处理
			access_token = generic_access_token(openid)
			return Response({'access_token': access_token})
		else:
			# 没有异常走else
			# 如果有  则说明用户绑定过
			# 应该跳转到首页去
			# 登录成功了，我们应该返回token
			from rest_framework_jwt.settings import api_settings

			jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
			jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

			payload = jwt_payload_handler(qquser.user)
			token = jwt_encode_handler(payload)

			return Response({
				'token': token,
				'username': qquser.user.username,
				'user_id': qquser.user.id
			})

	"""
	当用户输入完绑定信息之后，前端应该将 手机号，密码，短信验证码，openid(处理过的)传递给后端

	1.接收数据
	2.对数据进行校验(手机号，密码，短信验证码，openid(处理过的))
		2.1短信验证码
		2.2openid（处理过的）
		2.3根据手机号查询用户信息，判断是否存在

	3.保存数据
	4.返回响应

	POST
	"""
	def post(self,request):
		# 1.接收数据
		data = request.data
		#2.对数据进行校验
		serializer = OauthQQUserSerilizer(data=data)
		serializer.is_valid(raise_exception=True)
		#3.保存数据
		qquser = serializer.save()
		#4.返回响应
		from rest_framework_jwt.settings import api_settings

		jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
		jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

		payload = jwt_payload_handler(qquser.user)
		token = jwt_encode_handler(payload)

		return Response({
			'token': token,
			'username': qquser.user.username,
			'user_id': qquser.user.id
		})



from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from django.conf import settings

# 1.创建序列化器
# secret_key			密钥，我们一般使用的是文件中的SECRT_KEY
# expires_in=None		过期时间，单位是秒数
serializer = Serializer(settings.SECRET_KEY, 3600)

# 2.组织数据
data = {'openid': '1234567890'}

# 3.对数据进行加密
token = serializer.dumps(data)

# 解密
serializer.loads(token)